<?php
header('Content-Type: application/json');

$path = $_POST['path'] ?? '';
$path = preg_replace('/[<>"\\\\\/\|?:*\x00-\x1F]/u', '_', $path);
$uploadDir = "uploads/{$path}";

if (strpos(realpath($uploadDir), realpath('uploads')) !== 0) {
    die(json_encode(['error' => '路径超出允许范围'], JSON_UNESCAPED_UNICODE));
}

if (!isset($_FILES['file']) || $_FILES['file']['error'] != UPLOAD_ERR_OK) {
    $errorCode = $_FILES['file']['error'] ?? UPLOAD_ERR_NO_FILE;
    $errorMessages = [
        UPLOAD_ERR_INI_SIZE => '文件超过了服务器允许的大小上限',
        UPLOAD_ERR_FORM_SIZE => '文件超过了表单设置的大小上限',
        UPLOAD_ERR_PARTIAL => '文件只上传了一部分',
        UPLOAD_ERR_NO_FILE => '没有文件被上传',
        UPLOAD_ERR_NO_TMP_DIR => '服务器缺少临时文件夹',
    ];

    die(json_encode(['error' => $errorMessages[$errorCode] ?? '未知错误'], JSON_UNESCAPED_UNICODE));
}

$title = isset($_POST['title']) ? $_POST['title'] : uniqid();
$file = $_FILES['file'];

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$filename = preg_replace('/[<>"\\\\\/\|?:*\x00-\x1F]/u', '_', $title);
$tmpName = $file['tmp_name'];
$destination = "$uploadDir/{$filename}";

if (file_exists($destination)) {
    unlink($destination);
}

if (move_uploaded_file($tmpName, $destination)) {
    $response = [
        'url' => $destination,
    ];
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode(['error' => '文件上传失败'], JSON_UNESCAPED_UNICODE);
}
